package com.julang.check.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.julang.check.bean.User;
import com.julang.check.annotation.NotNeedToken;
import com.julang.check.api.mapper.UserMapper;
import com.julang.check.exception.UserNotExistException;
import com.julang.check.exception.UserNotLoginException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static com.julang.check.utils.CommonData.SWAGGERURLS;
import java.util.HashMap;
import java.util.Map;
/**
 * @author 赵自强
 * */
public class AuthenticationInterceptor implements HandlerInterceptor {

    private UserMapper userMapper;

    public AuthenticationInterceptor(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) {
        for (int i = 0; i < SWAGGERURLS.length; i++) {
            if (httpServletRequest.getRequestURI().startsWith(SWAGGERURLS[i])) {
                return true;
            }
        }
        /**从 http 请求头中取出 token*/
        String token = httpServletRequest.getHeader("Authorization");
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(NotNeedToken.class)) {
            NotNeedToken passToken = method.getAnnotation(NotNeedToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 执行认证
        if (token == null) {
            System.out.println("Empty Token");
            System.out.println(httpServletRequest.getRequestURI());
            throw new UserNotLoginException("Empty Token");
        }


        // 获取 token 中的 user id
        String userId = JWT.decode(token).getAudience().get(0);
        if (userMapper == null) {
            System.out.println("userMapper == null");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            System.out.println("user 不存在所以抛出");
            throw new UserNotExistException(token);
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("401");
        }
        return true;
    }
}
